import { isNavigationFailure, Router } from 'vue-router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { storage } from '@/utils';
import { MutationType } from '@/enums/userEnums';
import store from '@/store';
import { LayoutMutationType } from '@/enums/layoutEnums';
import { UserActionTypes } from '@/enums/userEnums';

NProgress.configure({ showSpinner: false });

export const notNeedLogin: string[] = ['Login', 'NotFound'];

// 登录路由
const loginRoutePath = '/login';
// 默认(首页)路由
const defaultRoutePath = '/goods';

// isGetMenus 是否需要接口获取路由

export function routerGuards(router: Router): void {
    router.beforeEach((to, from, next) => {
        NProgress.start(); // start progress bar
        const token = storage.get(MutationType.SetToken);
        if (token) {
            if (to.name === 'Login') {
                store.commit(LayoutMutationType.SetLock, false);
                next({ path: defaultRoutePath });
                NProgress.done();
            } else {
                // 获取当前用户菜单
                console.log(store.state.layout.menus);
                // if (!store.state.layout.menus.length) {
                //     console.log('dfdfdfdf');
                //     // 处理菜单函数放到vuex里面
                //     store.dispatch(UserActionTypes.GetMenu).then((v) => {
                //         // 抛出处理后的菜单数据
                //         // 通过菜单动态插入菜单
                //         // router.addRoute(info)
                //     });
                // }

                //
                store.dispatch(UserActionTypes.GetMenu).then((v) => {
                    // 抛出处理后的菜单数据
                    // 通过菜单动态插入菜单
                    // router.addRoute(info)
                });
                const hasRoute = router.hasRoute(to.name!);

                if (to.path == from.path) {
                    next({ path: '/redirect' + to.path });
                }
                if (notNeedLogin.includes(to.name as string) || hasRoute) {
                    // 在免登录名单，直接进入
                    next();
                }
            }
        } else {
            store.commit(LayoutMutationType.SetLock, false);
            // not login
            if (notNeedLogin.includes(to.name as string)) {
                // 在免登录名单，直接进入
                next();
            } else {
                next({
                    path: loginRoutePath,
                    query: { redirect: to.fullPath },
                    replace: true,
                });
                NProgress.done(); // if current page is login will not trigger afterEach hook, so manually handle it
            }
        }
    });

    router.afterEach((to, from, failure) => {
        if (isNavigationFailure(failure)) {
            console.log('failed navigation', failure);
        }
        NProgress.done(); // finish progress bar
    });

    router.onError((error) => {
        console.log(error, '路由错误');
    });
}
